package com.ohuang.test_compose.composeView


import android.os.Parcel
import android.os.Parcelable
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.lifecycle.MutableLiveData

/**
val controller= rememberSaveable() {
PageNavHostController()
}
PageNavHost(controller =controller, defaultKey ="CanvasPage"){
add("CanvasPage"){ CanvasPage()}
add("ImagePage"){ ImagePage()}
add("TextPage"){ TextPage() }
}
controller.navigation("CanvasPage") //use the fun to  replace   page
 *
 */
class PageNavHostController() : Parcelable {
    private var state = MutableLiveData<String>()
    private var key: String? = null

    private var map = HashMap<String, (@Composable() () -> Unit)>()
    private var mapCallback = HashMap<String, ((Boolean) -> Unit)>()

    private var pageNavHostManager = PageNavHostManager()

    constructor(parcel: Parcel) : this() {
        key = parcel.readString()
    }

    @Composable
    fun CreatePageNavHost(defaultKey: String, scope: (PageNavHostManager) -> Unit = {}) {
        key ?: apply {
            navigation(defaultKey)
        }
        scope(pageNavHostManager)
        PageNavHostImp()

    }

    @Composable
    private fun PageNavHostImp() {
        val state by state.observeAsState()
        if (state != null) {
            key?.let {
                mapCallback[key]?.invoke(false)
            }
            map[state]?.invoke()
            mapCallback[state]?.invoke(true)
            key = state
        }
    }

    private fun remove(key: String) {
        map.remove(key)
        mapCallback.remove(key)
    }

    private fun removeAll() {
        map.clear()
        mapCallback.clear()
    }

    inner class PageNavHostManager {
        /**
         * removeCallBack() 启动结束回调  true为启动 false为关闭
         */
        fun add(
            key: String,
            callBack: ((Boolean) -> Unit) = {},
            content: (@Composable() () -> Unit)
        ) {
            map[key] = content
            mapCallback[key] = callBack
        }

    }

    fun navigation(key: String) {
        state.value = key
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(key)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<PageNavHostController> {
        override fun createFromParcel(parcel: Parcel): PageNavHostController {
            return PageNavHostController(parcel)
        }

        override fun newArray(size: Int): Array<PageNavHostController?> {
            return arrayOfNulls(size)
        }
    }


}

@Composable
fun PageNavHost(
    controller: PageNavHostController,
    defaultKey: String,
    builder: PageNavHostController.PageNavHostManager.() -> Unit = {}
) {
    controller.CreatePageNavHost(defaultKey, builder)
}